package com.hycc.base;

public class VolatileNoAtomic {
    /*
    // synchronized 可以保证结果为 2w
    private static int num = 0;
    public synchronized static void add(){
        num++;
    }*/

    //volatile不能保证结果为 2w
    private volatile static int num = 0;
    public static void add(){
        num++;
    }

    public static void main(String[] args) {
        for (int i = 1; i <= 20; i++) {
            new Thread(()->{
                for (int j = 0; j < 1000; j++) {
                    add();
                }
            }).start();
        }
        while (Thread.activeCount()>2){
            Thread.yield();
        }
        System.out.println(num);

    }
}
